<template>
  <div class="main_box" style="padding: 10px">
    <!-- 中间部分 -->
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ $route.query.id ? '修 改 医 院 项 目 组 信 息' : '新 增 医 院 项 目 组' }}</h2>
        <div>
          <el-tooltip class="item" effect="dark" content="关联医院(子)项目可多选" placement="top-end">
            <i class="el-icon-info"></i>
          </el-tooltip>
          <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList(0)"> 返 回</el-button>
        </div>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules" style="margin: 0">
        <el-row>
          <el-form-item label="项目组名称" prop="itemName" style="width: 100%">
            <el-input v-model="dataForm.itemName" clearable style="width: 100%" maxlength="30" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="项目组别称" prop="itemShortName">
            <el-input v-model="dataForm.itemShortName" clearable></el-input>
          </el-form-item>
          <el-form-item label="项目组编号" prop="itemCode">
            <el-input v-model="dataForm.itemCode" clearable maxlength="30" show-word-limit></el-input>
          </el-form-item>
          <HospitalSelect @hospitalId="getHospitalId" :id="dataForm.hospitalId" :site="1" :disabled="modifyDisabled"> </HospitalSelect>
          <el-form-item label="原价格" prop="itemPrice">
            <el-input v-model="dataForm.itemPrice" type="number"></el-input>
          </el-form-item>
          <el-form-item label="合作价格" prop="itemSalePrice">
            <el-input v-model="dataForm.itemSalePrice" type="number"></el-input>
          </el-form-item>
          <div v-if="!$route.query.id">
            <!-- 关联子菜单 -->
            <el-form-item label="关联医院(子)项目" prop="subItemIdList" style="width: 100%">
              <el-select v-model="dataForm.subItemIdList" multiple filterable style="width: 100%" placeholder="请选择医院子项目" :loading="loadingIns">
                <el-option v-for="item in pickSubItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-col :span="24">
            <el-form-item label="临床意义" prop="itemMeaning" style="width: 100%">
              <el-input type="textarea" v-model="dataForm.itemMeaning" autosize placeholder="请输入临床意义"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注意事项" prop="itemNote" style="width: 100%">
              <el-input type="textarea" v-model="dataForm.itemNote" autosize placeholder="请输入注意事项"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" style="width: 100%">
              <el-input type="textarea" autosize v-model="dataForm.remark"></el-input>
            </el-form-item>
          </el-col>

          <!-- 表单保存和提交 -->
          <el-row v-if="$route.query.id">
            <el-form-item>
              <el-button type="primary" @click="sureDrugClick">保 存 基 本 信 息</el-button>
              <el-button @click="returnList(0)">取 消</el-button>
            </el-form-item>
          </el-row>

          <div class="tit" style="margin-bottom: 30px">
            <h2>{{ !$route.query.id ? '' : '修 改 ' }}关 联 信 息</h2>
          </div>

          <el-table :data="hospitalList">
            <el-table-column type="index" label="序号" align="center" width="200"></el-table-column>
            <el-table-column prop="institutionName" label="医检机构名称" align="center"></el-table-column>
            <el-table-column prop="discount" label="折扣说明" align="center" />
          </el-table>

          <el-col>
            <h2 style="margin-left: 20px">康来项目组</h2>
            <el-form ref="searchForm" :model="filters" :inline="true" class="inner-form">
              <el-form-item prop="methodology">
                <el-select v-model="filters.methodology" clearable filterable placeholder="请选择方法学">
                  <el-option v-for="item in methodologyList" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="feeLevel">
                <el-select v-model="filters.feeLevel" clearable filterable placeholder="请选择收费级别">
                  <el-option v-for="item in feeLevelList" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="addressList">
                <Address @getAddress="getAddress" :addressList="filters.addressList" :isCheckStrictly="true"></Address>
              </el-form-item>
              <el-form-item>
                <el-button size="mini" type="primary" @click="listReportItem">查询</el-button>
                <el-button size="mini" @click="reset">重置</el-button>
                <el-button size="mini" type="success" @click="getInstitutionItems">获取医检项目组</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-table ref="reportItemTable" :data="pickReportItemIdList" max-height="800px" style="margin-bottom: 10px" @select="handleSelection" @select-all="handleAllSelection">
            <el-table-column type="selection" label="选中" width="100" align="center"></el-table-column>
            <el-table-column label="项目名" prop="itemName" width="200" align="center"></el-table-column>
            <el-table-column label="省市" width="200" align="center">
              <template slot-scope="{ row: { provinceName, cityName } }">
                <span>{{ provinceName + (cityName ? '、' + cityName : '') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="收费级别" prop="feeLevel" width="150" align="center"></el-table-column>
            <el-table-column label="发光学" prop="methodology" width="150" align="center"></el-table-column>
            <el-table-column label="价格(元)" prop="itemPrice" align="center"></el-table-column>
          </el-table>
          <el-col :span="24">
            <h2 style="margin-left: 20px">医检项目组</h2>
          </el-col>
          <el-table :data="dataForm.hosItemIns" max-height="800px" style="margin-bottom: 10px; width: fit-content; max-width: fit-content">
            <el-table-column label="医检名称" prop="institutionName" width="200" align="center"></el-table-column>
            <el-table-column label="项目名称" prop="insItemName" width="200" align="center"> </el-table-column>
            <el-table-column label="方法学" prop="insItemMethodology" width="150" align="center"></el-table-column>
            <el-table-column label="医检原价" prop="insItemPrice" width="150" align="center"></el-table-column>
            <el-table-column label="医检合作价" prop="insItemSalePrice" width="150" align="center"></el-table-column>
            <el-table-column prop="repo rtItem" align="center" width="200">
              <template slot="header" slot-scope="scope">
                <span style="color: #369b88">康来价格（参考）</span>
              </template>
            </el-table-column>
            <el-table-column label="医院原价" width="150" align="center">
              <template slot-scope="{ row }">
                <el-input v-maxnum="{ obj: row, key: 'hosItemPrice', length: 2, zero: true }" :min="0" type="number" v-model="row.hosItemPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="医院合作价" prop="hosItemSalePrice" width="150" align="center">
              <template slot-scope="{ row, $index }">
                <el-input
                  type="number"
                  :min="0"
                  v-maxnum="{ obj: row, key: 'hosItemSalePrice', length: 2, zero: true }"
                  v-model="row.hosItemSalePrice"
                  @change="handleHosItemSalePriceChange(row, $index)"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-row v-if="!$route.query.id">
          <el-form-item>
            <el-button type="primary" @click="sureDrugClick">保 存</el-button>
            <el-button @click="returnList(0)">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <!-- 编辑 -->
      <div v-if="$route.query.id">
        <el-form :model="dataForm" label-width="200px" style="margin: auto 0">
          <el-form-item label="关联医院(子)项目" prop="subItemIdList" style="width: 100%">
            <el-select v-model="dataForm.subItemIdList" multiple filterable style="width: 100%" placeholder="请选择医院子项目" :loading="loadingIns">
              <el-option v-for="item in pickSubItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 表单保存和提交 -->
          <el-form-item>
            <el-button type="primary" @click="sureSubmit">保 存 关 联 信 息</el-button>
            <el-button @click="returnList">取 消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import HospitalSelect from '@/components/HospitalSelect';
import HospitalItemApi from '@/api/institution/hospitalItem';
import ReportItemApi from '@/api/report/reportItem';
import InstitutionItemApi from '@/api/institution/institutionItem';
import Address from '../../components/Address.vue';
import HospitalApi from '../../api/institution/hospital';
export default {
  data() {
    return {
      roleRules: {
        itemName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur',
          },
        ],
        hospitalId: [
          {
            required: true,
            message: '请选择对应医院',
            trigger: 'change',
          },
        ],
      },
      modifyDisabled: false,
      filters: {
        feeLevel: '',
        methodology: '',
        addressList: [],
      },
      dataForm: {
        // 表单数据
        itemId: '',
        itemName: '',
        itemShortName: '',
        itemCode: '',
        hospitalId: '',
        itemPrice: '',
        itemSalePrice: '',
        itemMeaning: '',
        itemNote: '',
        subItemIdList: [], // 关联子项目
        reportItemId: '',
        baseItemId: '',
        // itemIdList: "",

        // listA:[
        //   {id:1,itemName:"血常规",provinceName:"湖南省",cityName:"长沙市",feeLevel:"一类",methodology:"发光学",price:12},
        //   {id:2,itemName:"血常规",provinceName:"湖北省",cityName:"武汉市",feeLevel:"二类",methodology:"发光学",price:12},
        //   {id:3,itemName:"免疫",provinceName:"湖北省",cityName:"武汉市",feeLevel:"二类",methodology:"发光学",price:12},
        // ],
        // listB:[
        //   {id:1,institutionName:"浏阳中医院",institutionItemName:"小明机构",institutionPrice:"",institutionCpPrice:"",hosItemPrice:"",methodology:"发光学",hosItemSalePrice:"",reportPrice:""},
        //   {id:2,institutionName:"长沙医院",institutionItemName:"小明机构",institutionPrice:"",institutionCpPrice:"",hosItemPrice:"",methodology:"发光学",hosItemSalePrice:"",reportPrice:""},
        //   {id:3,institutionName:"湖南医院",institutionItemName:"小白机构",institutionPrice:"",institutionCpPrice:"",hosItemPrice:"",methodology:"发光学",hosItemSalePrice:"",reportPrice:""},
        // ],
        hosItemIns: [], // 医检项目列表
        remark: '',
      },
      loadingIns: false,
      selectedItems: [],
      pickSubItemIdList: [], // 子项目列表
      pickReportItemIdList: [], // 报告单项目列表
      methodologyList: [
        { id: '化学发光学', name: '化学发光学' },
        { id: '胶体金法', name: '胶体金法' },
        { id: '其它', name: '其它' },
      ],
      feeLevelList: [
        { id: '一类', name: '一类' },
        { id: '二类', name: '二类' },
        { id: '三类', name: '三类' },
      ],
      hospitalList: [],
    };
  },
  components: {
    HospitalSelect,
    Address,
  },
  mounted() {
    this.init();
    if(this.$route.query.hospitalFindId){
      this.dataForm.hospitalId = this.$route.query.hospitalFindId
      this.getHospitalId(this.dataForm.hospitalId)
    }
  },
  watch: {
    'dataForm.hospitalId': {
      handler(hospitalId) {
        HospitalApi.getHospital({ hospitalId }).then((res) => {
          const { institutionRelation } = res.data;
          if (institutionRelation && institutionRelation.length > 0) {
            this.hospitalList = institutionRelation;
          }
        });
      },
    },
  },
  methods: {
    init() {
      //  this.listReportItem();
      if (this.$route.query.id) {
        this.dataForm.itemId = parseInt(this.$route.query.id);
        this.getData();
      }
    },
    // 全选
    handleAllSelection(e) {
      // const {pickReportItemIdList} = this
      // if(e.length&&e.some((item,index)=>index&&item.itemName!==e[index-1].itemName)){
      //   this.$refs.reportItemTable.clearSelection()
      //   this.$message.error("只能选择相同项目的")
      //   pickReportItemIdList.forEach(item=>this.$delete(item,'state'))
      // }else{
      //   pickReportItemIdList.forEach(item=>this.$set(item,'state',1))
      // }
      // this.getInstitutionItems()
      if (e.length && e.some((item, index) => index && item.itemName !== e[index - 1].itemName)) {
        this.$refs.reportItemTable.clearSelection();
        this.$message.error('只能选择相同项目的');
        return;
      }
    },
    // 单选
    handleSelection(e) {
      if (e.length > 1 && e.at(-1).itemName !== e.at(-2).itemName) {
        this.$message.error('只能选择相同项目的');
        this.$refs.reportItemTable.toggleRowSelection(e.at(-1));
        return;
      } else {
        this.selectedItems = e;
      }
      // const {pickReportItemIdList} = this
      // const filterList = pickReportItemIdList.filter(item=>item.state)
      // if(filterList.length>0&&filterList.length<e.length&&!filterList.some(item=>item.itemName==e.at(-1).itemName)){
      //   this.$message.error("只能选择相同项目的")
      //   // 选中一个与前面选中项目不同的项目，不可以选中
      //   this.$refs.reportItemTable.toggleRowSelection(e.at(-1))
      //   return
      // }
      // pickReportItemIdList.forEach(item=>{
      //   if(e.some(item2=>item2.id==item.id)){
      //     this.$set(item,'state',1)
      //   }else{
      //     this.$delete(item,'state')
      //   }
      // })
      // this.selectedItems = e
      // console.log(e)
      // this.getInstitutionItems()
    },
    // 判断数据是否一样，项目名、省市、发光学、收费等级一样才是一样的数据
    // 获取医检项目
    async getInstitutionItems() {
      if (!this.selectedItems.length) {
        return this.$message.error('请先选择康来项目组');
      }
      const baseItemId = this.selectedItems[0].itemId;
      this.dataForm.baseItemId = baseItemId;
      const { data } = await InstitutionItemApi.listByBaseItem({ baseItemId });
      data.forEach((item) => {
        this.$set(item, 'hosItemPrice', '');
        this.$set(item, 'hosItemSalePrice', '');
        item.insItemId = item.itemId;
        item.insItemName = item.itemName;
        item.insItemPrice = item.itemPrice;
        item.insItemSalePrice = item.itemSalePrice;
        item.insItemMethodology = item.methodology;
      });
      this.dataForm.hosItemIns = data;
      const val = this.selectedItems
        .map((item) => item.provinceName + (item.cityName ? item.cityName : '') + '、' + item.feeLevel + '、' + item.methodology + '、' + item.itemPrice + '元')
        .join(',');
      this.dataForm.hosItemIns.forEach((item) => (item.reportItem = val));
    },
    // search(){
    //   this.listReportItem()
    // },
    reset() {
      // this.filters.provinceId = ''
      // this.filters.cityId = ''
      this.$refs.searchForm.resetFields();
      console.log(this.filters.addressList);
    },
    sureSubmit() {
      this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
        this.editData(true);
      });
    },
    getAddress({ provinceId, cityId }) {
      this.filters.addressList = provinceId ? [provinceId, cityId] : [];
    },

    checkData() {
      const { hosItemIns } = this.dataForm;
      this.hosItemIns = hosItemIns.map((item) => ({
        institutionId: item.institutionId,
        insItemId: item.insItemId,
        hosItemPrice: item.hosItemPrice,
        hosItemSalePrice: item.hosItemSalePrice,
      }));
    },
    sureDrugClick() {
      // 提交
      let _this = this;
      _this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.dataForm.itemId) {
            //做一个基础的判断，id不为空就编辑，id为空就增加
            this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
              this.editData();
            });
          } else {
            //  if(this.dataForm.subItemIdList.length<1&&this.dataForm.itemIdList.length<1){
            //   this.$message('医院项目组或者医院子项目必须选一个');
            //   return
            // }
            this.$confirm(message.MSG_CONFIRM_SAVE_ADD, message.TITLE_PROMPT, {}).then(() => {
              this.addData();
            });
          }
        }
      });
    },
    addData() {
      let _this = this; //限制作用域
      let cond = {
        // 表单数据
        itemName: _this.dataForm.itemName,
        itemShortName: _this.dataForm.itemShortName,
        itemCode: _this.dataForm.itemCode,
        hospitalId: _this.dataForm.hospitalId,
        subItemIdList: _this.dataForm.subItemIdList, // 关联子项目
        baseItemId: _this.dataForm.baseItemId,
        hosItemIns: _this.dataForm.hosItemIns,
        // itemIdList: _this.dataForm.itemIdList,
        itemPrice: _this.dataForm.itemPrice,
        itemSalePrice: _this.dataForm.itemSalePrice,
        itemMeaning: _this.dataForm.itemMeaning,
        itemNote: _this.dataForm.itemNote,
        remark: _this.dataForm.remark,
      };
      HospitalItemApi.addHospitalItem(cond).then((data) => {
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS,
        });
        this.returnList(cond);
      });
    },
    editData(flag = false) {
      // 编辑
      let _this = this;
      let cond = {
        itemId: _this.dataForm.itemId,
        itemName: _this.dataForm.itemName,
        itemShortName: _this.dataForm.itemShortName,
        itemCode: _this.dataForm.itemCode,
        hospitalId: _this.dataForm.hospitalId,
        subItemIdList: _this.dataForm.subItemIdList, // 关联子项目
        baseItemId: _this.dataForm.baseItemId,
        hosItemIns: _this.dataForm.hosItemIns,
        itemPrice: _this.dataForm.itemPrice,
        itemSalePrice: _this.dataForm.itemSalePrice,
        itemMeaning: _this.dataForm.itemMeaning,
        itemNote: _this.dataForm.itemNote,
        remark: _this.dataForm.remark,
      };
      if (flag) {
        cond.update = 2;
      }
      HospitalItemApi.editHospitalItem(cond).then((data) => {
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS,
        });
        this.returnList(cond);
      });
    },
    getData() {
      // 编辑前，获取数据
      let _this = this;
      this.modifyDisabled = true;
      HospitalItemApi.getHospitalItem({ itemId: _this.$route.query.id }).then((res) => {
        this.$Utils.bindingBean(this.dataForm, res.data);
        this.dataForm.subItemIdList = res.data.subItemIdList;
        this.dataForm.baseItemId = res.data.baseItemId;
        if (res.data.reportItemId) {
          this.dataForm.reportItemId = parseInt(res.data.reportItemId);
        }
        if (res.data.hospitalId) {
          this.dataForm.hospitalId = parseInt(res.data.hospitalId);
        }
        this.listHospitalSubItem(res.data.hospitalId);
      });
    },
    listHospitalItem(val) {
      // 获取医院项目组列表
      let _this = this;
      let cond = {
        hospitalId: val,
      };
      _this.loadingIns = true;
      HospitalItemApi.listHospitalItemsName(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.hosItemIns = res.data.map((item) => {
            return {
              value: item.itemId,
              label: item.itemName,
            };
          });
        }, 200);
      });
    },
    listHospitalSubItem(val) {
      // 获取医院子项目列表
      let _this = this;
      _this.loadingIns = true;
      var cond = {
        hospitalId: String(val),
        state: 1,
      };
      HospitalItemApi.listHospitalSubItems(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.pickSubItemIdList = res.data.map((item) => {
            return {
              value: item.subItemId,
              label: item.subItemName,
            };
          });
        }, 200);
      });
    },
    async listReportItem() {
      if (!this.dataForm.itemName) {
        this.$message.error('请先输入项目组名称');
        return;
      }
      // 获取报告单项目组列表
      const { filters } = this;
      const params = { ...filters, name: this.dataForm.itemName };
      params.provinceId = filters.addressList[0] || '';
      params.cityId = filters.addressList[1] || '';
      delete params.addressList;
      const { data } = await ReportItemApi.getReportItemsNameList(params);
      this.pickReportItemIdList = data;
      // setTimeout(() => {
      //   _this.pickReportItemIdList = res.data.map(item => {
      //     return {
      //       value: item.itemId,
      //       label: item.itemName
      //     };
      //   });
      // }, 200);
    },
    getHospitalId(val) {
      this.dataForm.subItemIdList = []; // 关联子项目
      // this.dataForm.itemIdList = [],
      // 将组件中的id 附给搜索的按钮
      this.dataForm.hospitalId = String(val);
      // this.hosItemIns = [];
      // this.listHospitalItem(val);
      this.pickSubItemIdList = [];
      this.listHospitalSubItem(val);
    },
    returnList(val) {
      let _this = this;
      if (val) {
        _this.$store.dispatch('delView', this.$route);
        _this.$router.push({
          path: '/items/hospitalItemManagement',
          query: { id: val.hospitalId },
        });
      } else {
        this.$store.dispatch('delView', this.$route);
        this.$router.push('/items/hospitalItemManagement');
        // _this.$router.go(-1);
      }
    },

    /**
     * 医院合作家inputchange
     */
    handleHosItemSalePriceChange(row, index) {
      if (row.hosItemSalePrice * 0.8 < row.insItemSalePrice) {
        this.$confirm(`${row.institutionName} 医院合作价过低, 是否确认`, '警告', {
          distinguishCancelAndClose: true,
          cancelButtonText: '取消输入',
          confirmButtonText: '确定输入',
        }).catch(() => {
          this.dataForm.hosItemIns[index].hosItemSalePrice = '';
        });
      }
    },
  },
};
</script>

<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
.add_wrap {
  padding-top: 10px;
  padding-left: 23px;
}
.inner-form {
  /* width: calc(100vw - 200px); */
  .el-form-item {
    width: fit-content !important;
  }
}
</style>
